<template>
  <el-dialog :title="!dataForm.id ? '调拨单新增' : '调拨单修改'" :close-on-click-modal="false" :visible.sync="visible" fullscreen center>
    <el-button class="miui-dialog-close-btn" @click="visible = false">关闭页面</el-button>
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" label-width="90px">
      <el-row>
        <el-col :span="8">
          <el-form-item label="调拨单号" >
            <el-input v-model="dataForm.billId" readonly></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="制单人" >
            <el-input v-model="this.userInfo.realName" readonly></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="单据日期" >
            <el-input v-model="dataForm.createTime" readonly></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="发出部门" prop="outDeptId">
            <el-select v-model="dataForm.outDeptId" placeholder="请选择" @change="getOutStockList" :disabled="userInfo.lessDeptId != 1">
              <el-option v-for="item in deptOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="发出仓库" prop="outStockId">
            <el-select v-model="dataForm.outStockId" placeholder="请选择" @change="getOutStockName">
              <el-option v-for="item in outStockOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="接收部门" prop="inDeptId">
            <el-select v-model="dataForm.inDeptId" placeholder="请选择" @change="getInStockList">
              <el-option v-for="item in inDeptOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="接收仓库" prop="inStockId">
            <el-select v-model="dataForm.inStockId" placeholder="请选择">
              <el-option v-for="item in inStockOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="供货商">
            <el-select v-model="dataForm.supplierId" placeholder="请选择">
              <el-option v-for="item in supplierOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注" class="miui-textarea" style="width: 100%;">
            <el-input v-model="dataForm.memo" type="textarea" style="width: 100%;"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="20">
          <el-form-item label-width="0">
            <el-button type="primary" @click="openTableList('single')">单品添加商品</el-button>
            <el-button type="primary" @click="openTableList('allot')">按调拨单添加商品</el-button>
            <el-button type="primary" @click="openTableList('receipt')">按收货单添加商品</el-button>
            <el-button type="primary" @click="barcodeScan()">条码扫描</el-button>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item style="float: right;">
            <el-button type="danger" @click="delTableData">删除</el-button>
          </el-form-item>
        </el-col>
      </el-row>


      <el-table
        :data="dataList"
        border
        v-loading="dataListLoading"
        header-cell-class-name="miui-header-cell-style"
        :row-class-name="addClass"
        show-summary  :summary-method="getSummaries"
        @cell-dblclick="quantityCopy"
        @selection-change="handleSelectionChange">
        <el-table-column key="1" type="selection" width="40"></el-table-column>
        <el-table-column key="2" prop="goodsCode" label="商品代码" width="170"></el-table-column>
        <el-table-column key="3" prop="viewGoodsName" label="商品名称" width="230"></el-table-column>
        <el-table-column key="4" prop="spec" label="型号" width="100"></el-table-column>
        <el-table-column key="5" prop="storageQuantity" label="可调用数量" width="100"></el-table-column>
        <el-table-column key="6" prop="price" label="零售价格" width="100"></el-table-column>
        <el-table-column key="7" prop="allocationQuantity" label="调拨数量" width="100">
          <template slot-scope="scope">
            <el-form-item :prop="'detailList.' + scope.$index + '.allocationQuantity'" :rules="dataRule.allocationQuantity" label-width="0px">
              <el-input v-model="scope.row.allocationQuantity" @input="allocationQuantityChangeHandle(scope.row,scope.$index)" :ref="'number'+scope.$index" @keyup.enter.native="enterChange(scope.$index)"></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column key="8" label="批次">
          <template slot-scope="scope">
            <el-input v-model="scope.row.batch"  v-if="scope.row.ctgId == '4' || scope.row.ctgId == '5' || scope.row.ctgName == '隐形' || scope.row.ctgName == '护理液'"></el-input>
          </template>
        </el-table-column>
        <el-table-column key="9" label="效期">
          <template slot-scope="scope">
            <el-input v-model="scope.row.invalidTime" v-if="scope.row.ctgId == '4' || scope.row.ctgId == '5' || scope.row.ctgName == '隐形' || scope.row.ctgName == '护理液'"></el-input>
          </template>
        </el-table-column>
        <el-table-column key="10" label="注册证号">
          <template slot-scope="scope">
            <el-input v-model="scope.row.registerNum"></el-input>
          </template>
        </el-table-column>
        <el-table-column key="11" prop="productionDate" width="110" label="生产日期"></el-table-column>
        <el-table-column key="12" label="生产厂家">
          <template slot-scope="scope">
            <el-input v-model="scope.row.manufacturerName"></el-input>
          </template>
        </el-table-column>
        <el-table-column key="13" prop="goodsBarcode" width="210" label="商品条码"></el-table-column>
      </el-table>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">关闭</el-button>
      <el-button type="primary" @click="dataFormSubmit()" :loading="ischeck" v-prevent-re-click>保存</el-button>
      <el-switch v-model="dataForm.allocationStatus" active-text="保存并审核" inactive-value="1" active-value="2" style="margin-left: 15px;"></el-switch>
    </span>
    <bill-list v-if="singleListVisible" ref="billOrSingle" @showBrandList="getBrandData"></bill-list>
    <!-- 弹窗，调拨单查询 -->
    <search-allot v-if="allotVisible" ref="allotDialog" :checkStock="this.dataForm.outStockId" @refreshData="getAllotData"></search-allot>
    <!-- 弹窗，收货单查询 -->
    <search-receipt v-if="receiptVisible" ref="receiptDialog" :checkStock="this.dataForm.outStockId" @refreshData="getReceiptData"></search-receipt>
    <!-- <order-detail v-if="detailVisible" ref="detailDialog"></order-detail> -->
    <!-- 弹窗，条码扫描  -->
    <barcode-scan v-if="barcodeVisible" ref="barcodeDialog" @refreshData="getBarcodeGoodsData"></barcode-scan>
  </el-dialog>
</template>

<script>
    import {mapGetters} from 'vuex'
    import { filterParams } from '@/util/tools'
    import * as check from '@/util/check/check'

    import {getStockFetchList,allocationAdd,allocationGetObj,allocationEdit} from '@/api/eims/allocation'
    import {getSupplierInfoList} from '@/api/eims/supplier'
    import {getDeptInfo,getDeptInfoByDeptType,getDeptInfoByDeptTypes,getObj} from '@/api/admin/dept'
    import {getStockList} from '@/api/eims/stock'
    import { getInfoParam } from '@/api/admin/sys-public-param'

    import BillList from '@/components/business/GoodsStorage'
    import SearchAllot from './bill/allot/SearchAllot'
    import SearchReceipt from './bill/receipt/SearchReceipt'
    import BarcodeScan from '@/components/business/BarcodeScan'
    // import BillList from './billlist'


    // import OrderDetail from './detail'

    export default {
    data () {
      return {
        visible: false,
        ischeck: false,
        singleListVisible: false,
        allotVisible: false,
        receiptVisible: false,
        detailVisible: false,
        dataListLoading: false,
        barcodeVisible: false,
        dataForm: {
          allocationStatus: '1',  // 是否审核
          billId: '',   // 调拨单号
          linkBillId: '', //   关联单号
          outDeptId: '',  // 发出部门
          outDeptName: '',
          outStockId: '', // 发出仓库
          inDeptId: '', //  接收部门
          inDeptName: '',
          inStockId: '',  //  接收仓库
          createUser: 1, //  制单人
          //modifyUser: '', // 修改用户
          //updateTime: '', // 修改时间
          supplierId: '',
          returnFlag: 1,
          detailList: []
        },
        flag: false,
        dataList: [],
        deptOptions: [],
        inDeptOptions: [],
        outStockOptions: [],
        inStockOptions: [],
        supplierOptions: [],
        selectionList: [],
        dataRule: {
          outDeptId: [{ required: true, message: '请选择发出部门',trigger: 'blur'}],
          outStockId: [{ required: true, message: '请选择发出仓位',trigger: 'blur'}],
          inDeptId: [{ required: true, message: '请选择接收部门',trigger: 'blur'}],
          inStockId: [{ required: true, message: '请选择接收仓位',trigger: 'blur'}],
          allocationQuantity: [{validator: check.checkIsInteger,trigger: 'blur'}]
        }
      }
    },
    components: {
      BillList,
      SearchAllot,
      SearchReceipt,
      // OrderDetail
      BarcodeScan
    },
    computed: {
      ...mapGetters(['userInfo'])
    },
    methods: {
      init (type,id) {
        this.addDate()
        this.getSupplierList()
        this.getFlag()
        this.dataForm.detailList = []
        this.dataList = []
        this.dataForm.id = id || 0
        this.dataForm.returnFlag = type
        this.$set(this.dataForm,'memo','')
        this.visible = true

        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          this.getDeptList()
          this.dataForm.outDeptId = this.userInfo.lessDeptId
          this.dataForm.outDeptName = this.userInfo.lessDeptName
          this.getOutStockList (this.userInfo.lessDeptId)
          if (this.dataForm.id) {
            allocationGetObj(this.dataForm.id).then(response => {
              if(response.data.code == '0'){
                this.getInStockList(response.data.data.inDeptId)
                this.getOutStockList(response.data.data.outDeptId)
                this.dataForm = response.data.data
                this.dataList = response.data.data.detailList
                this.dataList.forEach(item => {
                  let code = item.code || item.goodsCode
                  item.goodsBarcode = code.replace(/[\ |\.]/g,"") + ((item.invalidTime) ? (item.invalidTime.replace(/[\ |\-]/g,"")).substring(2,10) : '00000000')
                  item.viewGoodsName = item.goodsName
                })
              }else{
                this.$message.error(response.data.msg)
              }
            })
          }
        })
      },
      //判断门店上游供货商是否必填标志
      getFlag(){
        getInfoParam('SUPPLIER_STATUS',2,this.userInfo.unitId).then(response => {
          if(response.data.code == '0'){
            this.flag = response.data.data.publicValue
            this.flag = (this.flag == 'true') ? true : false
          }else{
            this.$message.error(response.data.msg)
          }

        })
      },
      // 获取部门列表
      getDeptList () {
        var data ={
          deptTypes : [1,2,3]
        }
        getDeptInfoByDeptTypes(data).then(response => {
          if(response.data.code == '0'){
            this.deptOptions = response.data.data
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      // 获取出库仓位列表
      getOutStockList(id) {
        this.deptOptions.forEach(item => {
          if(item.id == id){
            this.dataForm.outDeptName = item.name
          }
        })
        if(id){
          getStockList({deptId: id}).then(response => {
            if(response.data.code == '0'){
              this.outStockOptions = response.data.data
              if(this.outStockOptions.length > 0){
                this.dataForm.outStockId = this.outStockOptions[0].id
              }else{
                this.dataForm.outStockId = ''
              }
            }else{
              this.$message.error(response.data.msg)
            }
          })
        }else{
          this.$message.warning('请选择发出部门')
        }
        this.inDeptOptions =[]
        this.inStockOptions = []
        this.dataForm.inDeptName = ''
        this.dataForm.inDeptId = ''
        this.dataForm.inStockId = ''
        getObj(id).then(response => {
          if(response.data.code == '0'){
            if(response.data.data.deptType == 3){
              this.inDeptOptions = this.deptOptions
            }else{
              getObj(1).then(result2 =>{
                if(result2.data.code == '0'){
                  this.inDeptOptions.push(result2.data.data)
                }else{
                  this.$message.error(result2.data.msg)
                }
              })
            }
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      getOutStockName(val) {
        this.outStockOptions.forEach(item => {
          if(item.id == val) {
            this.dataForm.outStockName = item.name
          }
        })
      },
      // 获取入库仓位列表
      getInStockList (id) {
        //  获取接收部门名称
        this.deptOptions.forEach(item => {
          if(item.id == id){
            this.dataForm.inDeptName = item.name
          }
        })
        if(id){
          getStockList({deptId: id}).then(response => {
            if(response.data.code == '0'){
              this.inStockOptions = response.data.data
              if(this.inStockOptions.length > 0){
                this.dataForm.inStockId = this.inStockOptions[0].id
              }else{
                this.dataForm.inStockId = ''
              }
            }else{
              this.$message.error(response.data.msg)
            }
          })
        }else{
          this.$message.warning('请选择接收部门')
        }
      },
      //获取供货商列表
      getSupplierList(){
        getSupplierInfoList().then(result =>{
          if(result.data.code == '0'){
            this.supplierOptions = result.data.data
          }else{
            this.$message.error(result.data.msg)
          }
        })
      },
      //  回车切换下一行商品数量
      enterChange(index){
        if(this.$refs['number'+(index*1 + 1)]){
          this.$refs['number'+(index*1 + 1)].focus()
        }
      },
      //  调拨数量修改
      allocationQuantityChangeHandle(data,index) {
        this.dataList = [...this.dataList]
      },
      // 表单提交
      dataFormSubmit() {
        if(this.dataForm.inStockId){
          if(this.dataForm.outStockId == this.dataForm.inStockId){
            this.$message.warning('发出仓位和接收仓位不能一致')
            return false
          }
          if(this.flag){
            if(this.dataForm.supplierId == 0){
              this.$message.warning('请选择供货商')
              return false
            }
          }
          if(this.dataList.length == 0){
            this.$message.warning('请先选择商品')
            return false
          }
          for(let i=0;i<this.dataList.length;i++){
            if(parseFloat(this.dataList[i].allocationQuantity) <= parseFloat(this.dataList[i].storageQuantity) && parseFloat(this.dataList[i].allocationQuantity) > 0){
            }else{
              this.$message.warning("调拨数量不大于0或调拨数量大于库存，请重新输入调拨数量");
              return;
            }
            if (this.dataList[i].ctgId ==4 || this.dataList[i].ctgId==5) {
              if(!this.dataList[i].invalidTime){
                this.$message.warning("请输入效期");
                return;
              }
              if(!this.dataList[i].batch){
                this.$message.warning("请输入批号")
                return
              }
            }
          }
          this.dataForm.createTime = ''
          this.ischeck = true
          this.$refs['dataForm'].validate((valid) => {
            if (valid) {
              let list = []
              this.dataForm.detailList.forEach((item,index) => {
                if(this.dataList[index]){
                  item.allocationQuantity = this.dataList[index].allocationQuantity || 1
                }
                list.push(filterParams(item))
              })
              // this.dataForm.detailList = [...this.dataList]

              if (this.dataForm.id) {
                allocationEdit(this.dataForm).then(response => {
                  if(response.data.code == '0'){
                    (this.dataForm.allocationStatus == '1')?this.$message.success('修改成功'):this.$message.success('修改并审核成功')
                    this.visible = false
                    this.$emit('refreshDataList')
                  }else{
                    this.$message.error(response.data.msg)
                  }
                  this.ischeck = false
                }).catch(() => {
                  this.ischeck = false
                })
              } else {
                allocationAdd(this.dataForm).then(response => {
                  if(response.data.code == '0'){
                    (this.dataForm.allocationStatus == '1')?this.$message.success('添加成功'):this.$message.success('添加并审核成功')
                    this.visible = false
                    this.$emit('refreshDataList')
                  }else{
                    this.$message.error(response.data.msg)
                  }
                  this.ischeck = false
                }).catch(() => {
                  this.ischeck = false
                })
              }
            }else{
              this.ischeck = false
            }
          })
        }else{
          this.$message.warning('请选择接收仓位')
        }
      },
      // 按单品添加商品
      openTableList (name) {
        this.getOutStockName(this.dataForm.outStockId)
        let params = {
          stockId: this.dataForm.outStockId,
          stockName: this.dataForm.outStockName
        }
        let data = {
          paramsData: params,
          tableData: this.dataList
        }
        switch (name) {
          case 'single':
            if(!this.dataForm.outStockId){
              this.$message.warning('请选择发出仓位')
              return false
            }
            this.singleListVisible = true
            this.$nextTick(() => {
              this.$refs.billOrSingle.init(data)
            })
            break
          case 'allot':
            this.allotVisible = true
            this.$nextTick(() => {
              this.$refs.allotDialog.init()
            })
            break
          case 'receipt':
            this.receiptVisible = true
            this.$nextTick(() => {
              this.$refs.receiptDialog.init()
            })
            break
        }
      },
      // 多选表格表格变化事件
      handleSelectionChange (val) {
        this.selectionList = val
      },
      // 删除商品详情列表中的商品
      delTableData() {
        let list = JSON.parse(JSON.stringify(this.dataList))
        let detailList = JSON.parse(JSON.stringify(this.dataForm.detailList))
				this.selectionList.forEach((item,index) => {
				  for(let i = 0; i < list.length; i++){
				    if(list[i].goodsId == item.goodsId){
				      list.splice(i,1)
              detailList.splice(i,1)
				    }
				  }
				})
        this.selectionList = []
        this.dataList = [...list]
        this.dataForm.detailList = [...detailList]
      },
      // bill-list自定义事件
      getBrandData (data) {
        this.dataList = data
        let list = []
        data.forEach(item => {
          item.goodsCode = item.code || item.goodsCode
          item.goodsName = item.viewGoodsName || item.goodsName
          item.goodsId = item.goodsId || item.id
          item.price = item.goodsPrice || item.price
          delete item.id
          item.invalidTimeStr =(item.invalidStr)?item.invalidStr : (item.invalidTime) ? item.invalidTime.substring(0,10):''
          item.registerNum = (item.registerNum)?item.registerNum : null
          item.manufacturerName = (item.manufacturerName) ? item.manufacturerName : null
          if(item.ctgId == 4 || item.ctgId == 5){
            let code = item.code || item.goodsCode
            item.goodsBarcode = code.replace(/[\ |\.]/g,"") + ((item.invalidTimeStr ) ? (item.invalidTimeStr.replace(/[\ |\-]/g,"")).substring(2,10) : '000000') + 'A0'
          }else{
            let code = item.code || item.goodsCode
            item.goodsBarcode = code.replace(/[\ |\.]/g,"") + ((item.invalidTimeStr ) ? (item.invalidTimeStr.replace(/[\ |\-]/g,"")).substring(2,10) : '00000000')
          }
          list.push(item)
        })
        this.dataForm.detailList = list
      },
      getAllotData(data) {
        this.$set(this.dataForm,'inDeptId',data.inDeptId)
        this.getInStockList(data.inDeptId)
        this.$set(this.dataForm,'inStockId',data.inStockId)

        let list = []
        data.list.forEach(item => {
          item.viewGoodsName = item.goodsName
          item.invalidTimeStr =(item.invalidTime)?item.invalidTime.substring(0,10):''
          if(item.ctgId == 4 || item.ctgId == 5){
            let code = item.code || item.goodsCode
            item.goodsBarcode = code.replace(/[\ |\.]/g,"") + ((item.invalidTimeStr ) ? (item.invalidTimeStr.replace(/[\ |\-]/g,"")).substring(2,10) : '000000') + 'A0'
          }else{
            let code = item.code || item.goodsCode
            item.goodsBarcode = code.replace(/[\ |\.]/g,"") + ((item.invalidTimeStr ) ? (item.invalidTimeStr.replace(/[\ |\-]/g,"")).substring(2,10) : '00000000')
          }
          list.push(item)
        })
        this.dataList = list
        this.$set(this.dataForm,'detailList',list)
      },
      //  获取收货单商品
      getReceiptData(data) {
        let list = []
        data.forEach(item => {
          item.code = item.goodsCode
          item.viewGoodsName = item.goodsName
          item.storageQuantity = item.goodsQuantity
          item.allocationQuantity = item.quantity
          list.push(item)
        })
        this.dataList = list
        this.$set(this.dataForm,'detailList',list)
      },
      //  合计
      getSummaries(param) {
        const { columns, data } = param;
        const sums = [];
        columns.forEach((column, index) => {
          const values = data.map(item => Number(item[column.property]));
          if (!values.every(value => isNaN(value))) {
            if(index == 6){
              sums[index] = '合计： ' + values.reduce((prev, curr) => {
                const value = Number(curr);
                if (!isNaN(value)) {
                  return prev + curr;
                } else {
                  return prev;
                }
              }, 0)
            }
          }
        });
        return sums;
      },
      //  条码扫描
      barcodeScan() {
        if(!this.dataForm.inDeptId){
          this.$message.warning('请选择接收部门')
          return false
        }
        if(!this.dataForm.outStockId){
          this.$message.warning('请选择发出仓位')
          return false
        }
        this.barcodeVisible = true
        this.$nextTick(() => {
          this.$refs.barcodeDialog.init(this.dataForm.outStockId)
        })
      },
      //  条码扫描获取的数据
      getBarcodeGoodsData(data) {
        let obj = {...data}

        obj.goodsId = obj.id
        let result = this.dataForm.detailList.some(item => {
          return item.goodsBarcode == obj.goodsBarcode
        })

        if(result){
          this.dataForm.detailList.forEach(item => {
            if(item.goodsBarcode == obj.goodsBarcode){
              item.allocationQuantity += 1
            }
          })
        }else{
          obj.allocationQuantity = 1
          this.dataList.push(obj)
          this.dataForm.detailList.push(obj)
        }
      },
      //  调拨数量大于库存数量时，字体变成红色
      addClass({row,rowIndex}){
        if(row.storageQuantity*1 < row.allocationQuantity*1){
          return 'bgChange'
        }
      },
      //  双击向下复制数量
      quantityCopy(row,column,cell,event){
        this.$confirm('是否复制数量', '提示', {confirmButtonText: '确定',cancelButtonText: '取消',type: 'warning'}).then(() => {
          this.dataList.forEach(item => {
            item.allocationQuantity = row[column.property]
          })
          this.dataForm.detailList.forEach(item => {
            item.allocationQuantity = row[column.property]
          })
          this.dataList = [...this.dataList]
          this.dataForm.detailList = [...this.dataForm.detailList]
        })
      },
      //获取当前日期
      addDate() {
        let nowDate = new Date();
        let sysTime = {
            year: nowDate.getFullYear(),
            month: (nowDate.getMonth() + 1) < 10 ? "0" +(nowDate.getMonth() + 1) : (nowDate.getMonth() + 1),
            date: nowDate.getDate() < 10 ? "0" +nowDate.getDate() : nowDate.getDate(),
        }
        this.dataForm.createTime = sysTime.year + '-' + sysTime.month + '-'  + sysTime.date;
      }
    }
  }
</script>
<style lang="scss" scoped>
  /deep/ .el-table {
  display: flex;
  flex-direction: column;
  }

  /deep/ .el-table__body-wrapper {
  order: 1;
  }
  /deep/ .bgChange {
    color: red!important;
  }
</style>
